package com.newsinfo.service.impl;

import com.newsinfo.mapper.UserMapper;
import com.newsinfo.pojo.Result;
import com.newsinfo.pojo.User;
import com.newsinfo.service.UserService;
import com.newsinfo.utils.Md5Util;
import com.newsinfo.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    /**
     * 根据用户名查询用户
     * @param username
     * @return
     */
    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    /**
     * 注册
     * @param username
     * @param password
     */
    @Override
    public void register(String username, String password) {
        String md5Password = Md5Util.getMD5String(password);
        userMapper.register(username,md5Password);
    }

    /**
     * 更新用户基本信息
     * @param user
     */
    @Override
    public void updateUserInfo(User user) {
        userMapper.updateUserInfo(user);
    }

    /**
     * 更新用户头像
     * @param avatarUrl
     */
    @Override
    public void updateAvatar(String avatarUrl) {
        //通过ThreadLocal获取用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        userMapper.updateAvatar(avatarUrl,userId);
    }

    @Override
    public Result updatePwd(Map<String, String> params) {
        //获取数据
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        //数据校验
        if (oldPwd.isEmpty() || newPwd.isEmpty() || rePwd.isEmpty()){
            return Result.error("参数错误");
        }
        //判断旧密码是否正确
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = findByUsername(username);
        if (!user.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码不正确");
        }
        //判断新密码
        if (!newPwd.equals(rePwd)){
            return Result.error("两次密码不一致");
        }
        String md5NewPwd = Md5Util.getMD5String(newPwd);
        Integer userId = (Integer) map.get("id");
        userMapper.updatePwd(md5NewPwd,userId);
        return Result.success();
    }
}
